﻿using TouchSocket.Core;
using TouchSocket.Http;
using TouchSocket.Rpc;
using TouchSocket.WebApi;

namespace WebAPITest;

public partial class ApiServer : SingletonRpcServer
{
    private readonly ILog m_logger;

    public ApiServer(ILog logger)
    {
        this.m_logger = logger;
    }

    [WebApi(Method = HttpMethodType.Post)]
    public async Task<object> Upload(IWebApiCallContext ctx)
    {
        var request = ctx.HttpContext?.Request;
        Console.WriteLine("收到文件:"+request.ContentLength);
        if (request.ContentLength > 50 * 1024)
        {
            await ctx.HttpContext.Response.SetStatus(413, "FileTooLarge")
                     .SetContent(new { state = "failed", message = "FileTooLarge"}.ToJsonString())
                     .AnswerAsync();
            Console.WriteLine("发送413状态");
            return new {};
        }
        
        long totalRead = 0;

        // 最多读取到Content-Length为止
        while (totalRead < request.ContentLength)
        {
            using var block = await request.ReadAsync();
            if (block == null || block.Memory.IsEmpty)
            {
                break;
            }
            totalRead += block.Memory.Length;
            // 数据直接丢弃，不做任何处理

            // 如果流已完成，退出
            if (block.IsCompleted)
            {
                break;
            }
        }
        
        return new { state = "ok" };
    }
}